import datetime
from django.shortcuts import render, redirect
from app import models
from app.models import Kfv, Dwy, Kfc, Ph, Hma, Lz, Ddl
from django.core.paginator import Paginator

TYPE_HANDLERS = {
    'KFC': {
        'models': Kfc,
        'model': models.Kfc,
        'view_template': 'KFC/KFC_view.html',
        'approve_template': 'KFC/KFC_approve_view.html',
        'reject_template': 'KFC/KFC_reject.html',
        'report_template': "templates/template_KFC.xlsx"
    },
    'PH': {
        'models': Ph,
        'model': models.Ph,
        'view_template': 'PH/PH_view.html',
        'approve_template': 'PH/PH_approve_view.html',
        'reject_template': 'PH/PH_reject.html',
        'report_template': "templates/template_PH.xlsx"
    },
    'DWY': {
        'models': Dwy,
        'model': models.Dwy,
        'view_template': 'DWY/DWY_view.html',
        'approve_template': 'DWY/DWY_approve_view.html',
        'reject_template': 'DWY/DWY_reject.html',
        'report_template': "templates/template_DWY.xlsx"
    },
    'KFV': {
        'models': Kfv,
        'model': models.Kfv,
        'view_template': 'KFV/KFV_view.html',
        'approve_template': 'KFV/KFV_approve_view.html',
        'reject_template': 'KFV/KFV_reject.html',
        'report_template': "templates/template_KFV.xlsx"
    },
    'HMA': {
        'models': Hma,
        'model': models.Hma,
        'view_template': 'HMA/HMA_view.html',
        'approve_template': 'HMA/HMA_approve_view.html',
        'reject_template': 'HMA/HMA_reject.html',
        'report_template': "templates/template_HMA.xlsx"
    },
    'LZ': {
        'models': Lz,
        'model': models.Lz,
        'view_template': 'LZ/LZ_view.html',
        'approve_template': 'LZ/LZ_approve_view.html',
        'reject_template': 'LZ/LZ_reject.html',
        'report_template': "templates/template_LZ.xlsx"
    },
    'DDL':{
        'models': Ddl,
        'model': models.Ddl,
        'view_template': 'DDL/DDL_view.html',
        'approve_template': 'DDL/DDL_approve_view.html',
        'reject_template': 'DDL/DDL_reject.html',
        'report_template': "templates/template_DDL.xlsx"
    },
    
}

# 添加数字类型到文本的映射字典
TYPE_MAPPING = {
    1: 'KFC',
    2: 'PH',
    3: 'DWY',
    4: 'KFV',
    5: 'HMA',
    6: 'LZ',
    7: 'DDL',
}

def generate_form_data(request, form_type):
    handler = TYPE_HANDLERS.get(form_type)
    if handler is None:
        raise ValueError(f"未知的表单类型: {form_type}")
    
    """公共函数：处理表单生成的公共逻辑"""
    # 修改为获取所有工具并通过列表推导式过滤
    tools = [tool for tool in models.ToolInfo.objects.all() 
             if form_type in tool.type.split(',')]

    date = datetime.date.today().strftime('%Y-%m-%d')
    short_date = datetime.date.today().strftime('%m%d%y')
    year = datetime.date.today().strftime('%Y')
    count = handler['model'].objects.filter(date__startswith=year, type=form_type,
                                            user=request.unicom_username).count() + 1
    A1PH_Received02 = request.unicom_username + '-' + f"{count:03d}" + '-' + short_date + f"-{form_type}"
    return {
        'A1PH_Received02': A1PH_Received02,
        'date': date,
        'windows_user': request.unicom_full_name,
        'tools': tools
    }


def save_form_data(request, model_class, form_type):
    """公共函数：处理表单保存的公共逻辑"""
    data = request.POST.dict()
    form_data = model_class(
        all_data=data,
        c_number=request.POST.get('A1PH_Received02'),
        date=request.POST.get('A1PH_Rq07'),
        customer=request.POST.get('A1PH_Zsdw53'),
        snr=request.POST.get('A1PH_SN04'),
        user=request.unicom_username,
        type=form_type
    )
    form_data.save()
    return redirect('/list/')


def generate_pagination_html(paginator, page_number):
    elided_page_range = paginator.get_elided_page_range(page_number, on_each_side=1, on_ends=1)
    pagination_html = '<ul class="pagination pagination-sm">'

    # 添加上一页箭头
    if page_number > 1:
        pagination_html += f'<li class="page-item"><a class="page-link" href="?page={page_number - 1}">&laquo;</a></li>'
    else:
        pagination_html += '<li class="page-item disabled"><span class="page-link">&laquo;</span></li>'

    for page in elided_page_range:
        if page == paginator.ELLIPSIS:
            pagination_html += f'<li class="page-item disabled"><span class="page-link">{page}</span></li>'
        elif page == page_number:
            pagination_html += f'<li class="page-item active"><span class="page-link">{page}</span></li>'
        else:
            pagination_html += f'<li class="page-item"><a class="page-link" href="?page={page}">{page}</a></li>'

    # 添加下一页箭头
    if page_number < paginator.num_pages:
        pagination_html += f'<li class="page-item"><a class="page-link" href="?page={page_number + 1}">&raquo;</a></li>'
    else:
        pagination_html += '<li class="page-item disabled"><span class="page-link">&raquo;</span></li>'

    # 添加输入框和跳转按钮，使用Bootstrap样式美化
    pagination_html += '''
    <li class="page-item">
        <input type="text" class="form-control form-control-sm page-input" style="width: 60px; margin: 0 5px; display: inline-block;" placeholder="页码">
    </li>
    <li class="page-item">
        <button class="btn btn-sm btn-outline-primary" onclick="jumpToPage()">跳转</button>
    </li>
    '''

    pagination_html += '</ul>'
    return pagination_html


def get_paginated_data(request, queryset, page_size=30):
    """通用分页处理函数"""
    paginator = Paginator(queryset, page_size)
    try:
        page_number = int(request.GET.get('page', 1))
        page_number = max(1, min(page_number, paginator.num_pages))
    except (TypeError, ValueError):
        page_number = 1
    return paginator.get_page(page_number)


def get_merged_queryset(request, filter_args=None, order_by='-id'):
    """获取合并后的查询集"""
    if filter_args is None:
        filter_args = {}
    queryset = []
    for type_name, handler in TYPE_HANDLERS.items():
        if 'model' in handler:
            qs = handler['model'].objects.filter(user=request.unicom_username, **filter_args).order_by(order_by)
            queryset.extend(list(qs))
    queryset.sort(key=lambda x: getattr(x, 'date', getattr(x, 'id')), reverse=True)
    return queryset